'''
Created on Jul 31, 2014

@author: Siyuan Qi
'''

import os
import ctypes

# Dependencies
import pyglet
import pyglet.gl as gl
import numpy as np
import matplotlib.pyplot as plt

# Local imports
import plyio as ply
import pylab


class SceneRenderer(pyglet.window.Window):
	def __init__(self, cuboids, K, RT, **kwargs):
		def intrinToProj(K, width, height, znear, zfar):
			znear = float(znear)
			zfar = float(zfar)
			depth = zfar - znear
			q = -(zfar + znear) / depth
			qn = -2 * (zfar * znear) / depth
			proj = np.array([[ 2*K[0,0]/width, -2*K[0,1]/width, (-2*K[0,2]+width)/width, 0 ],
							 [  0,			  2*K[1,1]/height,( 2*K[1,2]-height)/height, 0],
							 [0,0,q,qn],  # This row is standard glPerspective and sets near and far planes.
							 [0,0,-1,0]]) # This row is also standard glPerspective.

			proj = map(float,proj.T.flat)
			proj = (gl.GLfloat * 16)(*proj)
			return proj

		super(SceneRenderer, self).__init__(**kwargs)

		self.K = K
		self.RT = RT

		# Calculate the projection matrix from the camera parameters
		znear, zfar = 0.001, 1000.
		self.proj = intrinToProj(self.K, self.width, self.height, znear, zfar)

		# Set modelview matrix for OpenGL rendering
		extrinsic = map(float, self.RT.T.flat)
		extrinsic = (gl.GLfloat * 16)(*extrinsic)
		gl.glMatrixMode(gl.GL_MODELVIEW)
		gl.glLoadMatrixf(extrinsic)
		gl.glEnable(gl.GL_DEPTH_TEST)

	def on_draw(self):
		# print "parent on_draw"
		self.clear()
		self.batch.draw()
		self.renderedData = np.fromstring(pyglet.image.get_buffer_manager().get_color_buffer().get_image_data().get_data('RGBA', self.width*4), np.uint8)
		self.imageData = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
		pyglet.app.exit()

	def on_resize(self, width, height):
		gl.glViewport(0, 0, width, height)
		gl.glMatrixMode(gl.GL_PROJECTION)
		gl.glLoadMatrixf(self.proj)
		gl.glMatrixMode(gl.GL_MODELVIEW)

		return pyglet.event.EVENT_HANDLED

	def getLineVertices(self, cuboid):
		x1 = cuboid[0]
		z1 = -cuboid[1]
		x2 = cuboid[2]
		z2 = -cuboid[3]
		x3 = cuboid[4]
		z3 = -cuboid[5]
		x4 = cuboid[6]
		z4 = -cuboid[7]

		y1 = cuboid[8]
		y2 = cuboid[9]

		A = [x1, y1, z1]
		B = [x2, y1, z2]
		C = [x3, y1, z3]
		D = [x4, y1, z4]
		E = [x1, y2, z1]
		F = [x2, y2, z2]
		G = [x3, y2, z3]
		H = [x4, y2, z4]

		return A+B + B+C + C+D + D+A + A+E + B+F + C+G + D+H + E+F + F+G + G+H + H+E

	def getCuboidVertices(self, cuboid):
		x1 = cuboid[0]
		z1 = -cuboid[1]
		x2 = cuboid[2]
		z2 = -cuboid[3]
		x3 = cuboid[4]
		z3 = -cuboid[5]
		x4 = cuboid[6]
		z4 = -cuboid[7]

		y1 = cuboid[8]
		y2 = cuboid[9]

		A = [x1, y1, z1]
		B = [x2, y1, z2]
		C = [x3, y1, z3]
		D = [x4, y1, z4]
		E = [x1, y2, z1]
		F = [x2, y2, z2]
		G = [x3, y2, z3]
		H = [x4, y2, z4]

		return A+B+F+E + B+C+G+F + A+B+C+D + C+D+H+G + D+A+E+H + E+F+G+H 



class OrientationMapRenderer(SceneRenderer):
	def __init__(self, cuboids, K, RT, **kwargs):
		super(OrientationMapRenderer, self).__init__(cuboids, K, RT, **kwargs)
		# print "OrientationMapRenderer"
		self.addRenderBatch(cuboids)
		self.set_visible (True)

	def addRenderBatch(self, cuboids):
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.structureLists = []
		self.structuresCount = 0
		self.structures = []
		self.entityLists = []
		self.entities = []
		self.entitiesCount = 0

		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] == 0:
				self.structures.extend(cuboid)
				self.structuresCount += 1

				vertices = super(OrientationMapRenderer, self).getLineVertices([c for c in cuboid])
				colors = (255, 255, 255)*24
# 				self.structureLists.append(self.batch.add(24, pyglet.gl.GL_LINES, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 1 or cuboid[10] == 2:
				self.entities.extend(cuboid)
				self.entitiesCount += 1

				vertices = super(OrientationMapRenderer, self).getCuboidVertices([c for c in cuboid])
				colors = ((0, 0, 255)*4 + (0, 255, 0)*4 + (255, 0, 0)*4)*2
				self.entityLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))


class SegmentationMapRenderer(SceneRenderer):
	def __init__(self, cuboids, K, RT, **kwargs):
		super(SegmentationMapRenderer, self).__init__(cuboids, K, RT, **kwargs)
		# print "SegmentationMapRenderer"
		self.addRenderBatch(cuboids)
		self.set_visible (True)

	def addRenderBatch(self, cuboids):
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.structures = []
		self.structuresCount = 0
		self.structureLists = []
		self.entities = []
		self.entitiesCount = 0
		self.entityLists = []
		self.background = []
		self.backgroundLists = []

		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] == 0:
				self.structures.extend(cuboid)
				self.structuresCount += 1

				vertices = super(SegmentationMapRenderer, self).getLineVertices([c for c in cuboid])
				colors = (255, 255, 255)*24
# 				self.structureLists.append(self.batch.add(24, pyglet.gl.GL_LINES, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 1:
				self.entities.extend(cuboid)
				self.entitiesCount += 1

				vertices = super(SegmentationMapRenderer, self).getCuboidVertices([c for c in cuboid])
				colors = (255, 0, 255)*24
				self.entityLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 2: 
				self.background.extend(cuboid)

				vertices = super(SegmentationMapRenderer, self).getCuboidVertices([c for c in cuboid])
				colors = (0, 0, 0)*4 + (0, 255, 255)*4 + (0, 255, 0)*4 + (255, 255, 0)*4 + (255, 0, 0)*4 + (0, 0, 255)*4 
				self.backgroundLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))


class ObjectMapRenderer(SceneRenderer):
	def __init__(self, cuboids, K, RT, **kwargs):
		super(ObjectMapRenderer, self).__init__(cuboids, K, RT, **kwargs)
		# print "ObjectMapRenderer"
		self.addRenderBatch(cuboids)
		self.set_visible (True)

	def addRenderBatch(self, cuboids):
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.frames = []
		self.framesCount = 0
		self.frameLists = []
	
		gl.glLineWidth(5)
		
		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] != 0:
				vertices = super(ObjectMapRenderer, self).getLineVertices([c for c in cuboid])
				colors = (255, 0, 0)*24
				self.frameLists.append(self.batch.add(24, pyglet.gl.GL_LINES, None, ('v3f', vertices), ('c3B', colors)))
	
		'''
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.structures = []
		self.structuresCount = 0
		self.structureLists = []
		self.entities = []
		self.entitiesCount = 0
		self.entityLists = []
		self.background = []
		self.backgroundLists = []

		
		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] == 0:
				self.structures.extend(cuboid)
				self.structuresCount += 1

				vertices = super(ObjectMapRenderer, self).getLineVertices([c for c in cuboid])
				colors = (255, 255, 255)*24
				self.structureLists.append(self.batch.add(24, pyglet.gl.GL_LINES, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 1:
				self.entities.extend(cuboid)
				self.entitiesCount += 1

				vertices = super(ObjectMapRenderer, self).getCuboidVertices([c for c in cuboid])
				colors = (cuboid[11], cuboid[12], cuboid[13])*24
				self.entityLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 2: 
				self.background.extend(cuboid)

				vertices = super(ObjectMapRenderer, self).getCuboidVertices([c for c in cuboid])
				colors = (0, 0, 0)*4 + (0, 255, 255)*4 + (0, 255, 0)*4 + (255, 255, 0)*4 + (255, 0, 0)*4 + (0, 0, 255)*4 
				self.backgroundLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))
		'''


class FrameDrawer(SceneRenderer):
	def __init__(self, cuboid, oriImg, K, RT, **kwargs):
		super(FrameDrawer, self).__init__(cuboid, K, RT, **kwargs)
		self.cuboid = cuboid
		
		self.batch = pyglet.graphics.Batch()
		self.image = pyglet.image.load(oriImg)
		
		self.clear()	
		self.addRenderBatch(cuboid)
		
		self.set_visible (True)
			
	def addRenderBatch(self, cuboid):
		# Initialize batch for OpenGL rendering
		self.frames = []
		self.framesCount = 0
		self.frameLists = []
	
		# Add the cuboids from file to the batch
		gl.glLineWidth(5)
		vertices = super(FrameDrawer, self).getLineVertices([c for c in cuboid])
		colors = (255, 0, 0)*24
		self.frameLists.append(self.batch.add(24, pyglet.gl.GL_LINES, None, ('v3f', vertices), ('c3B', colors)))
	
	def on_draw(self):
		self.image.blit(self.image.width/2, self.image.height/2, 0)
		self.batch.draw()
		self.imageData = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
		pyglet.app.exit()		


class Unprojector(SceneRenderer):
	def __init__(self, cuboids, K, RT, workPath, imgName, **kwargs):
		super(Unprojector, self).__init__(cuboids, K, RT, **kwargs)
		self.workPath = workPath
		self.imgName = imgName
		self.addRenderBatch(cuboids)
		self.set_visible (True)

	def addRenderBatch(self, cuboids):
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.entities = []
		self.entitiesCount = 0
		self.entityLists = []
		self.background = []
		self.backgroundLists = []

		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] == 1:
				self.entities.extend(cuboid)
				self.entitiesCount += 1

				vertices = super(Unprojector, self).getCuboidVertices([c for c in cuboid])
				colors = (cuboid[11], cuboid[12], cuboid[13])*24
				self.entityLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 2: 
				self.background.extend(cuboid)

				vertices = super(Unprojector, self).getCuboidVertices([c for c in cuboid])
				colors = (0, 0, 0)*4 + (0, 255, 255)*4 + (0, 255, 0)*4 + (255, 255, 0)*4 + (255, 0, 0)*4 + (0, 0, 255)*4 
				self.backgroundLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))

	def unProjectImage(self):
# 		global space
		# Based on: http://nehe.gamedev.net/data/articles/article.asp?article=13
		fouriv = ctypes.c_int * 4
		sixteendv = ctypes.c_double * 16
		viewport = fouriv()  # Where The Viewport Values Will Be Stored
		gl.glGetIntegerv(gl.GL_VIEWPORT, viewport)  # Retrieves The Viewport Values (X, Y, Width, Height)
		modelview = sixteendv()  # Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
		gl.glGetDoublev(gl.GL_MODELVIEW_MATRIX, modelview)  # Retrieve The Modelview Matrix
		projection = sixteendv()  # Where The 16 Doubles Of The Projection Matrix Are To Be Stored
		gl.glGetDoublev(gl.GL_PROJECTION_MATRIX, projection)  # Retrieve The Projection Matrix 
	
		def unProject(x, y, z, modelview, projection):
			X = ctypes.c_double()
			Y = ctypes.c_double()
			Z = ctypes.c_double()
			result = gl.gluUnProject(ctypes.c_double(x), ctypes.c_double(y), ctypes.c_double(z), modelview, 
				projection, viewport, ctypes.byref(X), ctypes.byref(Y), ctypes.byref(Z));
			return [X.value, Y.value, Z.value]
	
		zbuffer = np.empty((viewport[3],viewport[2]), dtype=np.float32)
		gl.glReadPixels(0, 0, viewport[2], viewport[3], gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, zbuffer.ctypes.data)
# 		imgplot = plt.imshow(zbuffer)
# 		imgplot.set_cmap('jet')
# 		plt.colorbar()
# 		pylab.show()
	
		oriImage = pyglet.image.load(self.workPath+"images/"+self.imgName)
		oriMap = np.fromstring(oriImage.texture.get_image_data().get_data('RGB', viewport[2]*3), np.uint8)
		im = oriMap.reshape(viewport[3],viewport[2],3);
# 		imgplot = plt.imshow(im)
# 		pylab.show()
	
		vert = []
		color = []
		face = []
		for u in range(0, viewport[2]):
			for v in range(0, viewport[3]):
				winx = viewport[2] - 1 - u
				winy = viewport[3] - 1 - v
				
				# vertex
				# The calculation true z as follows, but the unProject uses the window z directly from zbuffer
				# z = 2.0 * znear * zfar / (zfar + znear - (2.0 * zbuffer[v][u] - 1.0) * (zfar - znear))
				vt = unProject(winx, winy, zbuffer[v][u], modelview, projection)
				vert.append(vt)
				# color
				cl = np.array([im[v][u][0],im[v][u][1],im[v][u][2]])
				color.append(cl)
	
		# face
		index=0
		for u in range(0, viewport[2]):
			for v in range(0, viewport[3]):
				#print u,v,index
				index = index+1
				if u!=0 and v!=0:
					fc = np.array([u*viewport[3]+v, (u-1)*viewport[3]+v, (u-1)*viewport[3]+(v-1), u*viewport[3]+(v-1)])
					a = np.array(vert[u*viewport[3]+v])-np.array(vert[(u-1)*viewport[3]+(v-1)])
					b = np.array(vert[(u-1)*viewport[3]+v])-np.array(vert[u*viewport[3]+(v-1)])
					if (np.linalg.norm(a)<0.1 and np.linalg.norm(b)<0.1):
						face.append(fc)
	
		fname = self.workPath+"results/"+os.path.splitext(self.imgName)[0]+"/reconstruction.ply"
		if os.path.isfile(fname):
			os.remove(fname)
			
		# print "Writing ply file!"
		print ply.writePLY(fname,vert,color,face)
		pyglet.app.exit()

	def on_draw(self):
		self.clear()	
		self.batch.draw()
		# print "calling unprojectImage"
		self.unProjectImage()
		# print "unprojectImage called"
		pyglet.app.exit()
	
	
class DepthSaver(SceneRenderer):
	def __init__(self, cuboids, K, RT, folder, iteration, **kwargs):
		super(DepthSaver, self).__init__(cuboids, K, RT, **kwargs)
		self.folder = folder
		self.iteration = iteration
		self.addRenderBatch(cuboids)
		self.set_visible (True)

	def addRenderBatch(self, cuboids):
		# Initialize batch for OpenGL rendering
		self.batch = pyglet.graphics.Batch()
		self.entities = []
		self.entitiesCount = 0
		self.entityLists = []
		self.background = []
		self.backgroundLists = []

		# Add the cuboids from file to the batch
		for cuboid in cuboids:
			if cuboid[10] == 1:
				self.entities.extend(cuboid)
				self.entitiesCount += 1

				vertices = super(DepthSaver, self).getCuboidVertices([c for c in cuboid])
				colors = (255, 0, 255)*24
				self.entityLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))
			elif cuboid[10] == 2: 
				self.background.extend(cuboid)

				vertices = super(DepthSaver, self).getCuboidVertices([c for c in cuboid])
				colors = (0, 0, 0)*4 + (0, 255, 255)*4 + (0, 255, 0)*4 + (255, 255, 0)*4 + (255, 0, 0)*4 + (0, 0, 255)*4 
				self.backgroundLists.append(self.batch.add(24, pyglet.gl.GL_QUADS, None, ('v3f', vertices), ('c3B', colors)))

	def saveDepth(self):
		# Based on: http://nehe.gamedev.net/data/articles/article.asp?article=13
		# print "in saveDepth"
		fouriv = ctypes.c_int * 4
		sixteendv = ctypes.c_double * 16
		viewport = fouriv()  # Where The Viewport Values Will Be Stored
		gl.glGetIntegerv(gl.GL_VIEWPORT, viewport)  # Retrieves The Viewport Values (X, Y, Width, Height)
		modelview = sixteendv()  # Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
		gl.glGetDoublev(gl.GL_MODELVIEW_MATRIX, modelview)  # Retrieve The Modelview Matrix
		projection = sixteendv()  # Where The 16 Doubles Of The Projection Matrix Are To Be Stored
		gl.glGetDoublev(gl.GL_PROJECTION_MATRIX, projection)  # Retrieve The Projection Matrix 
	
		zbuffer = np.empty((viewport[3]-1,viewport[2]-1), dtype=np.float32)
		gl.glReadPixels(0, 0, viewport[2]-1, viewport[3]-1, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, zbuffer.ctypes.data)
		
# 		fig = plt.figure()
# 		ax = plt.axes([0, 0, 1, 1])
		imgplot = plt.imshow(zbuffer[::-1, :], interpolation='nearest')
		imgplot.set_cmap('jet')
		plt.axis('off')
		plt.savefig(self.folder+"depthMap_"+str(self.iteration)+".png", bbox_inches='tight')
		plt.clf()

	def on_draw(self):
		self.clear()	
		self.batch.draw()
		# print "calling saveDepth"
		self.saveDepth()
		pyglet.app.exit()


	
class LikelihoodModel:
	def __init__(self, data, workPath, imgName, cuboids = None):
		data_dir = os.path.split(os.path.abspath(__file__))[0]
		
		self.workPath = workPath
		self.imgName = imgName

		self.cuboids = self.processCuboids(cuboids)
		self.orientationMap = pyglet.image.load(data[0])
		self.segmentationMap = pyglet.image.load(data[1])
		self.K = data[2]
		self.RT = data[3]

		self.width = self.orientationMap.width
		self.height = self.orientationMap.height

		# Ground truth orientation map for comparison
		self.orientationMap = np.fromstring(self.orientationMap.texture.get_image_data().get_data('RGBA', self.width*4), np.uint8)
		self.segmentationMap = np.fromstring(self.segmentationMap.texture.get_image_data().get_data('RGBA', self.width*4), np.uint8)
		
		def calBlackPixels(arr):
			arr = arr == 0
			size = arr.size/4
			arr = arr.reshape((size, 4))
			return np.sum(np.logical_and(np.logical_and(arr[:, 0], arr[:, 1]), arr[:, 2]))
		
		self.offset = calBlackPixels(self.orientationMap)
		self.denominator = float(self.width*self.height)/250
# 		self.denominator = float(self.width*self.height)/5000


	def processCuboids(self, cuboids):
		def rotate(l, n):
			return l[n:] + l[:n]

		def processCuboid(cuboid):
			minAngle = np.inf
			rotateIndex = 8
			for i in range(0, 4):
				vec = np.array([cuboid[2*(i+1)%8] - cuboid[2*i], cuboid[(2*(i+1)+1)%8] - cuboid[2*i+1]])
				angle = np.arccos((cuboid[2*(i+1)%8] - cuboid[2*i])/np.linalg.norm(vec))
				if angle < minAngle:
					minAngle = angle
					rotateIndex = i
			return rotate(cuboid, 2*rotateIndex)

		if cuboids:
			for cuboid in cuboids:
				cuboid[0:8] = processCuboid(cuboid[0:8])
			return cuboids

	def calLikelihoodEnergy(self, cuboids):
		def partSum(arr):
			# Calculate the sum of RGB values in an RGBA array
			size = arr.size/4
			arr = arr.reshape((size, 4))
			return np.sum(np.logical_or(np.logical_or(arr[:, 0], arr[:, 1]), arr[:, 2]))

		def pixelDifference(renderedData, oringinalImageData):
			diff = oringinalImageData != renderedData
			pixelDifference = partSum(diff)
			return float(pixelDifference)

		self.cuboids = self.processCuboids(cuboids)
		self.logLikelihood = 0
		self.logLikelihood -= self.offset
		
		self.renderedImg = []

		self.sampledOrientation = OrientationMapRenderer(cuboids = self.cuboids, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
		pyglet.app.run()
		self.renderedImg.append(self.sampledOrientation.imageData)
		self.logLikelihood += pixelDifference(self.sampledOrientation.renderedData, self.orientationMap)
		self.sampledOrientation.close()

		self.sampledSegmentation = SegmentationMapRenderer(cuboids = self.cuboids, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
		pyglet.app.run()
		self.renderedImg.append(self.sampledSegmentation.imageData)
		self.logLikelihood += pixelDifference(self.sampledSegmentation.renderedData, self.segmentationMap)
		self.sampledSegmentation.close()
		
		# NORMALIZE
		#self.logLikelihood /= self.denominator
		self.logLikelihood /= 125

		return self.logLikelihood

	def saveMap(self, folder = None, img=None, saveply = False):
		if saveply:
			self.sampledObjects = ObjectMapRenderer(cuboids = self.cuboids, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
			pyglet.app.run()
			self.renderedImg.append(self.sampledObjects.imageData)
			self.sampledObjects.close()
		
			# print "Saving depth map"
			self.unprojector = DepthSaver(cuboids = self.cuboids, K = self.K, RT = self.RT, folder = folder, iteration = 'final', resizable = False, width = self.width, height = self.height, visible = False)
			pyglet.app.run()
			self.unprojector.close()
			
			# print "Saving ply file"
			self.unprojector = Unprojector(cuboids = self.cuboids, K = self.K, RT = self.RT, workPath = self.workPath, imgName = self.imgName, resizable = False, width = self.width, height = self.height, visible = False)
			pyglet.app.run()
			self.unprojector.close()
		else:
			self.sampledObjects = ObjectMapRenderer(cuboids = self.cuboids, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
			pyglet.app.run()
			self.renderedImg.append(self.sampledObjects.imageData)
			self.sampledObjects.close()
		
		if img:
			self.renderedImg[0].save(folder+str(img)+'_sampledOrientation.png')
			self.renderedImg[1].save(folder+str(img)+'_sampledSegmentation.png')
			self.renderedImg[2].save(folder+str(img)+'_sampledObjects.png')
		else:
			print "Error: result image file names missing!"


	def saveTemp(self, folder, iteration):
		self.sampledObjects = ObjectMapRenderer(cuboids = self.cuboids, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
		pyglet.app.run()
		self.renderedImg.append(self.sampledObjects.imageData)
		self.sampledObjects.close()
		
		self.renderedImg[0].save(folder+'sampledOrientation_'+str(iteration)+'.png')
		self.renderedImg[1].save(folder+'sampledSegmentation_'+str(iteration)+'.png')
		self.renderedImg[2].save(folder+'sampledObjects_'+str(iteration)+'.png')

		self.unprojector = DepthSaver(cuboids = self.cuboids, K = self.K, RT = self.RT, folder = folder, iteration = iteration, resizable = False, width = self.width, height = self.height, visible = False)
		pyglet.app.run()
		self.unprojector.close()
		
	def saveFrame(self, folder, cuboids, name):
		for i, cuboid in enumerate(cuboids):
			frameDrawer = FrameDrawer(cuboid = cuboid, oriImg = "../../images/"+self.imgName, K = self.K, RT = self.RT, resizable = False, width = self.width, height = self.height, visible = False)
			pyglet.app.run()
			frameDrawer.imageData.save(folder+'cuboid_'+name+'_'+str(i)+'.png')
			frameDrawer.close()
	

	